package com.srkj.component;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * zhangshaoxiong
 * com.srkj.component
 * 2018/6/2 15:44
 */
public class DateConverterConfig implements Converter<String,Date> {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortdateFormat = "yyyy-MM-dd HH:mm:ss";
    @Override
    public Date convert(String value) {
        if (StringUtils.isEmpty(value)){
            return null;
        }
        value = value.trim();
        try {
            if (value.contains("_")) {
                SimpleDateFormat format;
                if (value.contains(":")) {
                    format = new SimpleDateFormat(dateFormat);
                } else {
                    format = new SimpleDateFormat(shortdateFormat);
                }
                Date date = format.parse(value);

            } else if (value.matches("^\\d+$")) {
                Long lDate = new Long(value);
                return new Date(lDate);
            }
        }catch (Exception e){
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}
